#version 450
#extension GL_ARB_separate_shader_objects : enable

layout (binding = 1) uniform samplerCube samplerEnvMap;

layout(binding = 2) uniform Exposure {
	float exposure;
	float gamma;
} exposureUbo;

layout (location = 0) in vec3 inUVW;

layout(location = 0) out vec4 outColor;

const float A = 0.15;
const float B = 0.50;
const float C = 0.10;
const float D = 0.20;
const float E = 0.02;
const float F = 0.30;
const float W = 11.2;

// From http://filmicworlds.com/blog/filmic-tonemapping-operators/
vec3 Uncharted2Tonemap(vec3 color)
{
	return ((color*(A*color+C*B)+D*E)/(color*(A*color+B)+D*F))-E/F;
}

void main() {

	vec3 envColor = texture(samplerEnvMap, inUVW).rgb;

    // Tone mapping
	envColor = Uncharted2Tonemap(envColor * exposureUbo.exposure);
	envColor = envColor * (1.0f / Uncharted2Tonemap(vec3(W)));
	// Gamma correction
	envColor = pow(envColor, vec3(1.0f / exposureUbo.gamma));
	
	outColor = vec4(envColor, 1.0);
}